"""
Manage benchmarks

@author Patrice Ferlet <metal3d@gmail.com>
@licence GNU GPL v3
"""

from benchmark import Benchmark
import os, glob, subprocess, shlex

class Manager:
    def __init__(self, options):
        self.options = options
        self.bench = []
        self.getBenchmark()
        self.launch()

    def getBenchmark(self):
        for d in glob.glob(self.options.benchdir + "/*.bench"):
            benchfile = open(d,'r')
            content = benchfile.readlines()
            benchfile.close()

            state = None
            compilecommand = []
            launchcommand = []
            cleanup = []
            title = None

            prepare_part = ['::compile::', '::prepare::']
            launch_part  = ['::run::', '::launch::']
            clean_part   = ['::clean::', '::cleanup::']

            for l in content:
                l = l.strip().replace ("\n","")
                if len(l)<1:
                    continue

                if l[:1] == "=":
                    title = l[1:]
                    continue

                elif l in prepare_part:
                    state = 'compile'
                elif l in launch_part :
                    state = 'run'
                elif l in clean_part:
                    state = 'clean'
                else:
                    if state == 'compile':
                        compilecommand.append (l)
                    if state == 'clean':
                        cleanup.append(l);
                    if state == 'run':
                        launchcommand.append (l)
            self.bench.append( ( d , title, compilecommand, launchcommand, cleanup) )

    def launch(self, ):
        cwd = os.getcwd()                
        for b in self.bench:
            (name, title, compilecommand, launchcommand, cleanup) = b
            os.chdir(os.path.dirname(name));
            print "moving into: ", os.path.dirname(name)
            
            #prepare state
            if len(compilecommand) > 0:
                print "-- Compiling %s bench" % name
                c = "\n".join(compilecommand);
                print ">>"+c
                os.system(c)

            #launch state
            print "-- Launching Benchmark"
            launchcommand = " ".join(launchcommand)
            print ">>"+launchcommand
            b = Benchmark(self.options, launchcommand, title, name)

            #cleanup state
            if len(cleanup) > 0:
                print "-- Cleanup"
                c = "\n".join(cleanup)
                print ">>" + c
                os.system(c)
                    
        os.chdir (cwd)
